import React, { useState, useEffect } from 'react';
import { Card, Select, Spin, Typography, Collapse, Table, Divider, Tag } from 'antd';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts';
import ReactECharts from 'echarts-for-react';

const { Title, Text, Paragraph } = Typography;
const { Panel } = Collapse;
const { Option } = Select;

interface EdgePattern {
  source_type: string;
  edge_type: string;
  target_type: string;
  count: number;
}

interface PatternInstance {
  id?: string;
  type?: string;
  attributes?: Record<string, any>;
}

interface Pattern {
  id: string;
  node_types: Record<string, number>;
  edge_patterns: EdgePattern[];
  support: number;
  instances: PatternInstance[];
}

interface HGPMSResults {
  patterns: Pattern[];
  pattern_growth_history: number[];
  pattern_instances: Record<string, any[]>;
}

interface HGPMSVisualizerProps {
  loading: boolean;
  results?: {
    details?: {
      patterns?: Pattern[];
      patternGrowthHistory?: number[];
      parameters?: Record<string, any>;
      metrics?: any[];
      rawResponse?: string;
    };
  };
}

const HGPMSVisualizer: React.FC<HGPMSVisualizerProps> = ({ loading, results }) => {
  const [selectedPattern, setSelectedPattern] = useState<string | null>(null);

  useEffect(() => {
    // 选择支持度最高的模式
    if (results?.details?.patterns && results.details.patterns.length > 0) {
      setSelectedPattern(results.details.patterns[0].id);
    }
  }, [results]);

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
        <div style={{ marginTop: '20px' }}>正在处理异构图模式挖掘...</div>
      </div>
    );
  }

  if (!results || !results.details) {
    return <div>暂无挖掘结果</div>;
  }

  // 安全地访问数据，提供默认值
  const patterns = results.details.patterns || [];
  const patternGrowthHistory = results.details.patternGrowthHistory || [];
  const parameters = results.details.parameters || {};
  
  // 更新使用这些属性的地方
  const topPatterns = patterns.slice(0, 5);
  
  // 准备模式增长历史数据
  const growthData = patternGrowthHistory.map((count, index) => ({
    iteration: index + 1,
    count,
  }));

  // 找到当前选中的模式
  const currentPattern = patterns.find(p => p.id === selectedPattern);

  // 准备模式节点分布图数据
  const nodeDistributionOption = currentPattern
    ? {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        series: [
          {
            name: '节点分布',
            type: 'pie',
            radius: ['50%', '70%'],
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: true,
              formatter: '{b}: {c}',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold',
              },
            },
            data: Object.entries(currentPattern.node_types || {}).map(([type, count]) => ({
              name: type,
              value: count,
            })),
          },
        ],
      }
    : {};

  // 准备模式边分布图数据
  const edgeDistributionOption = currentPattern
    ? {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)',
        },
        series: [
          {
            name: '边分布',
            type: 'pie',
            radius: ['50%', '70%'],
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2,
            },
            label: {
              show: true,
              formatter: '{b}: {c}',
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '14',
                fontWeight: 'bold',
              },
            },
            data: currentPattern.edge_patterns 
              ? currentPattern.edge_patterns.map(edge => ({
                  name: `${edge.source_type}-[${edge.edge_type}]->${edge.target_type}`,
                  value: edge.count,
                }))
              : [],
          },
        ],
      }
    : {};

  // 模式实例表格列定义
  const columns = [
    {
      title: '实例节点ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text: string) => <Tag color="blue">{text}</Tag>,
    },
    {
      title: '属性',
      dataIndex: 'attributes',
      key: 'attributes',
      render: (attrs: Record<string, any>) =>
        Object.entries(attrs).map(([key, value]) => (
          <div key={key}>
            <Text type="secondary">{key}:</Text> {value.toString()}
          </div>
        )),
    },
  ];

  // 渲染实例时，添加额外检查
  const instancesData = currentPattern && currentPattern.instances
    ? (currentPattern.instances || []).slice(0, 10).map((instance, index) => {
        // 检查instance是否是对象
        if (typeof instance !== 'object' || instance === null) {
          return {
            key: index,
            id: '未知',
            type: '未知',
            attributes: {}
          };
        }
        
        // 安全地提取数据
        return {
          key: index,
          id: instance.id || '未知',
          type: instance.type || '未知',
          attributes: instance.attributes || {},
        };
      })
    : [];

  // 在组件中添加处理图表数据的逻辑
  const renderChartData = (chartData: any) => {
    if (!chartData || !Array.isArray(chartData)) {
      return null;
    }
    
    return chartData.map((item, index) => {
      if (item.type === 'chart') {
        // 根据图表类型选择合适的图表组件
        switch (item.data.type) {
          case 'line':
            return (
              <Card key={index} title={item.title} style={{ marginBottom: 16 }}>
                <p>{item.description}</p>
                <ReactECharts 
                  option={{
                    xAxis: item.data.config.xAxis,
                    yAxis: item.data.config.yAxis,
                    series: item.data.config.series,
                    tooltip: { trigger: 'axis' }
                  }} 
                  style={{ height: 300 }} 
                />
              </Card>
            );
          case 'bar':
            // 类似渲染条形图
            return <div key={index}>...</div>;
          default:
            return <div key={index}>不支持的图表类型: {item.data.type}</div>;
        }
      }
      
      // 非图表数据的处理
      return (
        <div key={index}>
          {typeof item === 'object' ? JSON.stringify(item) : item}
        </div>
      );
    });
  };

  return (
    <div className="hgpms-visualizer">
      <Title level={3}>异构图模式挖掘结果</Title>

      {patternGrowthHistory.length > 0 && (
        <Card style={{ marginBottom: 16 }}>
          <Title level={4}>模式增长历史</Title>
          <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={growthData}>
              <CartesianGrid strokeDasharray="3 3" />
              <XAxis dataKey="iteration" />
              <YAxis />
              <Tooltip />
              <Area type="monotone" dataKey="count" stroke="#8884d8" fill="#8884d8" />
            </AreaChart>
          </ResponsiveContainer>
          <Paragraph style={{ marginTop: 8 }}>
            图表展示了模式增长的迭代过程，共进行了 {growthData.length} 次迭代，最终发现了{' '}
            {patterns.length} 个频繁模式。
          </Paragraph>
        </Card>
      )}

      <Card>
        <div style={{ marginBottom: 16 }}>
          <Title level={4}>频繁模式详情</Title>
          <Select
            style={{ width: 300 }}
            placeholder="选择模式查看详情"
            value={selectedPattern}
            onChange={setSelectedPattern}
          >
            {topPatterns.map(pattern => (
              <Option key={pattern.id} value={pattern.id}>
                模式 {pattern.id} (支持度: {(pattern.support * 100).toFixed(2)}%)
              </Option>
            ))}
          </Select>
        </div>

        {currentPattern && (
          <>
            <Card type="inner" title="模式概览" style={{ marginBottom: 16 }}>
              <div style={{ display: 'flex', flexWrap: 'wrap' }}>
                <div style={{ flex: '1 1 200px', minWidth: '200px', padding: '8px' }}>
                  <Text strong>模式ID:</Text> {currentPattern.id}
                </div>
                <div style={{ flex: '1 1 200px', minWidth: '200px', padding: '8px' }}>
                  <Text strong>支持度:</Text> {(currentPattern.support * 100).toFixed(2)}%
                </div>
                <div style={{ flex: '1 1 200px', minWidth: '200px', padding: '8px' }}>
                  <Text strong>节点类型数:</Text> {Object.keys(currentPattern.node_types).length}
                </div>
                <div style={{ flex: '1 1 200px', minWidth: '200px', padding: '8px' }}>
                  <Text strong>边类型数:</Text> {currentPattern.edge_patterns.length}
                </div>
                <div style={{ flex: '1 1 200px', minWidth: '200px', padding: '8px' }}>
                  <Text strong>实例数:</Text> {currentPattern.instances.length}
                </div>
              </div>
            </Card>

            <div style={{ display: 'flex', flexWrap: 'wrap', marginBottom: 16 }}>
              <Card type="inner" title="节点分布" style={{ flex: '1 1 400px', minWidth: '400px', marginRight: 8 }}>
                <ReactECharts option={nodeDistributionOption} style={{ height: 300 }} />
              </Card>
              <Card type="inner" title="边分布" style={{ flex: '1 1 400px', minWidth: '400px', marginLeft: 8 }}>
                <ReactECharts option={edgeDistributionOption} style={{ height: 300 }} />
              </Card>
            </div>

            <Collapse defaultActiveKey={[]}>
              <Panel header="模式实例 (前10个)" key="instances">
                <Table
                  dataSource={instancesData}
                  columns={columns}
                  pagination={false}
                  size="small"
                  scroll={{ x: 'max-content' }}
                />
              </Panel>
            </Collapse>
          </>
        )}
      </Card>

      {/* 移除可能有问题的图表数据渲染 */}
      {/*
      {results?.details?.chartData && (
        <div>
          <Title level={4}>算法指标与图表</Title>
          {renderChartData(results.details.chartData)}
        </div>
      )}
      */}
    </div>
  );
};

export default HGPMSVisualizer; 